

import * as Cesium from 'cesium';
import { createCancelablePromise, createProcessingFromAsyncFunc, Destroyable, JsonValue } from 'xbsj-base';
import { ESCesiumViewer } from './index';
import { defaultCreateCesiumViewerFunc } from './defaultCreateCesiumViewerFunc';

function terrainHeightsinitialized() {
    return new Promise<void>((resolve, reject) => Cesium.GroundPolylinePrimitive.initializeTerrainHeights().then(resolve));
}

export class ViewerCreating extends Destroyable {
    constructor(subContainer: HTMLDivElement, czmViewer: ESCesiumViewer, setViewerFunc: (viewer: Cesium.Viewer | undefined) => void, czmOptions?: JsonValue) {
        super();

        const resetViewer = () => {
            czmViewer.setStaus('Raw');
            const { viewer } = czmViewer;
            if (viewer) {
                setViewerFunc(undefined);
                viewer.destroy();
            }
        };
        this.dispose(resetViewer);
        const createViewerProcessing = this.dv(createProcessingFromAsyncFunc<void, [container: HTMLDivElement]>(async (cancelsManager, subContainer) => {
            czmViewer.setStaus('Creating');
            czmViewer.setStatusLog('正在创建Cesium视口...');
            const createCesiumViewerFunc = defaultCreateCesiumViewerFunc;
            await cancelsManager.promise(terrainHeightsinitialized());
            const viewer = await cancelsManager.promise(createCancelablePromise(createCesiumViewerFunc(subContainer, czmOptions)));
            czmViewer.setStaus('Created');
            czmViewer.setStatusLog('成功创建Cesium视口!');
            setViewerFunc(viewer);
        }));
        createViewerProcessing.start(subContainer);
        createViewerProcessing.errorEvent.don(() => {
            czmViewer.setStaus('Error');
            czmViewer.setStatusLog('创建Cesium视口失败!');
        })
    }
}
